package GUILag;

import ControllerLag.CustomerCTR;
import ModelLag.Customer;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 * Dette Panel bruges til at vise de kunder som er i databasen, samt at oprette
 * eller redigere en kunde.
 * @author DM75 Gruppe 3.
 * @version 22-12-2011
 */
public class CustomerTablePanel extends javax.swing.JPanel {
    private CustomerCTR customerCTR;
    /** Creates new form CustomerPanel */
    public CustomerTablePanel() {
        initComponents();
        customerCTR = new CustomerCTR();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchLabel = new javax.swing.JLabel();
        searchTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        customerTable = new javax.swing.JTable();
        updCusButton = new javax.swing.JButton();
        createCusButton = new javax.swing.JButton();

        searchLabel.setText("Find kunde:");

        searchTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                searchTextFieldKeyReleased(evt);
            }
        });

        customerTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tlf", "Fornavn", "Efternavn", "Adresse", "Postnr", "By", "Email"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        customerTable.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(customerTable);

        updCusButton.setText("Rediger kunde");
        updCusButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updCusButtonActionPerformed(evt);
            }
        });

        createCusButton.setText("Opret kunde");
        createCusButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createCusButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(searchLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 163, Short.MAX_VALUE)
                        .addComponent(createCusButton)
                        .addGap(18, 18, 18)
                        .addComponent(updCusButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchLabel)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(updCusButton)
                    .addComponent(createCusButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    protected JTable getTable()
    {
        return customerTable;
    }
            
    
    protected DefaultTableModel getModel()
    {
        return (DefaultTableModel) customerTable.getModel();
    }
    
    private void addRowAndDataToCustomerTable(String phoneNo, String fName, String lName, String address, String zipCode, String city, String email)     
    {  
        Object[] data = {phoneNo, fName, lName, address, zipCode, city, email};
        getModel().addRow(data);
    }  
    
    private void updateTable()
    {
        getModel().setRowCount(0);
        if(!searchTextField.getText().equals(""))
        {
            for(Customer customerObj : customerCTR.searchCustomer(searchTextField.getText().trim()))
            {
                String phoneNo = customerObj.getPhoneNo();
                String fName = customerObj.getfName();
                String lName = customerObj.getlName();
                String address = customerObj.getAddress();
                String zipCode = customerObj.getZipCode();
                String city = customerObj.getCity();
                String email = customerObj.getEmail();
                addRowAndDataToCustomerTable(phoneNo, fName, lName, address, zipCode, city, email);
            }
        }
    }
    
    private void searchTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchTextFieldKeyReleased
        updateTable();
    }//GEN-LAST:event_searchTextFieldKeyReleased
    
    private void createCusButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createCusButtonActionPerformed
        JTextField phoneNoField = new JTextField();
        JTextField fNameField = new JTextField();
        JTextField lNameField = new JTextField();
        JTextField addressField = new JTextField();
        JTextField zipCodeField = new JTextField();
        JTextField emailField = new JTextField();
        int rc =0;
        
        // Strings og JTexFields som skal vises i JOptionpane.
        Object[] message = new Object[] {"Fornavn:", fNameField, "Efternavn:", lNameField, "Adresse:", addressField, "Post nr.:", zipCodeField, "Email:", emailField, "Telefon nr.:", phoneNoField};
        
        
        // En anden form for JOptionpane.
        //int input = JOptionPane.showConfirmDialog(this, message, "Opret ny kunder", JOptionPane.OK_CANCEL_OPTION); HER er OK Knappen i fokus fra start!
        
        //Knapper på JOptionpane, som der har knapperne "OK" og "Annuller".
        Object[] options = {"OK", "Annuller"};
        
        int input = JOptionPane.showOptionDialog(this, message, "Opret ny kunde", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");
        
        if(input == JOptionPane.OK_OPTION)
        {
            if (phoneNoField.getText().length() > 0 && phoneNoField.getText().length() < 13)
            {
               try
               {
                    rc = customerCTR.createCustomer(phoneNoField.getText(), fNameField.getText(), lNameField.getText(), addressField.getText(), zipCodeField.getText(), emailField.getText());
               }
               catch(Exception e)
               {
                   System.out.println(e.getMessage()); 
                   JOptionPane.showMessageDialog(this, "Der er opstået en fejl. Tjek om du har indtastet noget forkert", "oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
               }
                //rc = return code
                if(rc == 1)
                {
                    JOptionPane.showMessageDialog(this, "Kunden er oprettet.", "Oprettelse lykkedes", JOptionPane.INFORMATION_MESSAGE);
                    
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Der er opstået en fejl. Kunden" + fNameField.getText() + "" + lNameField.getText() + " eksisterer muligvis i forvejen.", "oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
                }
            }
            else
            {
                 JOptionPane.showMessageDialog(this, "Udfyld alle felter. Telefonnr maks. 12 cifre.", "Oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_createCusButtonActionPerformed

    private void updCusButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updCusButtonActionPerformed
        int rowSelected = customerTable.getSelectedRow();
        int rc = 0;
        if(rowSelected == -1)
        {
            JOptionPane.showMessageDialog(this ,"Vælg kunden som skal opdateres.", "Vælg medarbejderen", JOptionPane.INFORMATION_MESSAGE);
        }
        else
        {
            String phoneNo = (String) customerTable.getValueAt(rowSelected, 0);
            String fName = (String) customerTable.getValueAt(rowSelected, 1);
            String lName = (String) customerTable.getValueAt(rowSelected, 2);
            String address = (String) customerTable.getValueAt(rowSelected, 3);
            String zipCode = (String) customerTable.getValueAt(rowSelected, 4);
            String email = (String) customerTable.getValueAt(rowSelected, 6);
            JTextField fNameField = new JTextField(fName);
            JTextField lNameField = new JTextField(lName);
            JTextField addressField = new JTextField(address);
            JTextField zipCodeField = new JTextField(zipCode);
            JTextField emailField = new JTextField(email);

            Object[] message = new Object[] {"Telefon nr.:", phoneNo, "Fornavn:", fNameField, "Efternavn:", lNameField, "Adresse:", addressField, "Post nr.:", zipCodeField,"Email:", emailField};       
            Object[] options = { "Opdater", "Annuller"};
            
            //Bruges for at få fokus i det første textfield i JOptionpanet.
            int input = JOptionPane.showOptionDialog(this, message, "Opdatering af kunde", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");
            
            if(input == JOptionPane.OK_OPTION)
            {
                if(fNameField.getText().length() > 0)
                {
                                        try{
                    rc = customerCTR.updateCustomer(phoneNo, fNameField.getText(), lNameField.getText(), addressField.getText(), zipCodeField.getText(), emailField.getText());
                    }catch(Exception e)
                    {
                        System.out.println(e.getMessage());
                    }
                    if(rc == 1)
                    {
                        String city = customerCTR.findCustomer(phoneNo).getCity();
                        customerTable.setValueAt(phoneNo, rowSelected, 0);
                        customerTable.setValueAt(fNameField.getText(), rowSelected, 1);
                        customerTable.setValueAt(lNameField.getText(), rowSelected, 2);
                        customerTable.setValueAt(addressField.getText(), rowSelected, 3);
                        customerTable.setValueAt(zipCodeField.getText(), rowSelected, 4);
                        customerTable.setValueAt(city, rowSelected, 5);
                        customerTable.setValueAt(emailField.getText(), rowSelected, 6);
                        
                        JOptionPane.showMessageDialog(this, "Kunden er opdateret.", "Opdatering lykkedes", JOptionPane.INFORMATION_MESSAGE);  
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(this, "Postnr findes ikke, eller du indtastet for mange tegn i et af felterne.", "Opdatering mislykkedes", JOptionPane.ERROR_MESSAGE);
                    }
                }
                else
                {
                    JOptionPane.showMessageDialog(this, "Der skal indtastet de rigtige data.", "Oprettelse mislykkedes", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }//GEN-LAST:event_updCusButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createCusButton;
    private javax.swing.JTable customerTable;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JTextField searchTextField;
    private javax.swing.JButton updCusButton;
    // End of variables declaration//GEN-END:variables
}
